import SockJS from "sockjs-client";
import Stomp from "stompjs";

const connection = function (options) {
  const stompClient = Stomp.over(
    new SockJS(process.env.VUE_APP_BASE_API + "/ws"),
  );
  stompClient.debug = null;
  stompClient.connect(
    {},
    () => {
      stompClient.subscribe(options.subscribe, (msg) => {
        options.success(JSON.parse(msg.body));
      });
    },
    (err) => {
      console.log(err, "连接失败");
      connection(options);
    },
  );

  //  断开websocket连接
  this.$once("hook:beforeDestroy", () => {
    stompClient.disconnect();
    stompClient.disconnect();
  });
};

export default connection;
